﻿using QFramework;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
using YooAsset;

public class GameAppArchitecture : Architecture<GameAppArchitecture>
{
    protected override void Init()
    {
        this.RegisterModel(new QFYooassetModule());
        this.RegisterModel(new QFLubanModule());
        this.RegisterModel(new QFHyclrModule());
    }
}

public class HotfixGameAppMain : MonoBehaviour, IController
{

    private async void Awake()
    {
        DontDestroyOnLoad(this);
        //等待热更泛型补充AOT dll加载完成
#if !UNITY_EDITOR
        if (await this.SendQuery(new QueryHyclrLoadAotdlls()))
            StartGames();
#endif
#if UNITY_EDITOR
        //编辑器下可以直接运行
        StartGames();
#endif
    }

    private void StartGames()
    {
        //接受Model层发送过来的事件
        this.RegisterEvent<StartGamesEvent>(StartGames).UnRegisterWhenGameObjectDestroyed(gameObject);
    }

    async void StartGames(StartGamesEvent @event)
    {
        //手动初始化因为这个md是要在Yoomd下下载后调用的
        this.GetModel<QFLubanModule>().Init();

        //声音使用方法
        AudioKit.PlayMusic("game_pass", false);
        //开始使用
        var mresLoader = ResLoader.Allocate();
        mresLoader.LoadSync<GameObject>("yoo:test").Instantiate().Position(this.Position()).Show();

        //场景加载目前只能这样加载
        mresLoader.Add2Load("yoo:games", (a, b) =>
        {
            if (a)
            {
                var oper = SceneManager.LoadSceneAsync("games", LoadSceneMode.Single);
                while (true)
                {
                    if (oper.progress >= 0.9f)
                    {
                        break;
                    }
                    Debug.Log($"加载场景中...{oper.progress}");
                    Task.Delay(100);
                }
            }
        });
        mresLoader.LoadAsync();
        mresLoader.Recycle2Cache();
        mresLoader = null;

        this.SendCommand<CmdYooRelease>();
        

        //这里使用的是yoo的简写路径、可以再QFYooAssetsPanelLoaderPool中声明使用简写的路径
            //UIKit.OpenPanelAsync<UIGameStart>().ToAction().Start(this);
        //等待3秒消毁窗口
        await Awaitable.WaitForSecondsAsync(3);
            //UIKit.ClosePanel<UIGameStart>();

        //测试luban加载
        this.GetModel<QFLubanModule>().tables.TbItem.Get(10001).Id.LogInfo();

    }


    public IArchitecture GetArchitecture()
    {
        return GameAppArchitecture.Interface;
    }
}



